<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import useUserStore from '@/store/modules/user'
import { useRouter,useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

const loginForm = ref({
  username: 'admin',
  password: '111111'
})
//获取el-form实例
const loginFormRef = ref()
//登录按钮回调
const login = async () => {
  //保证表单全部填写再发送请求
  await loginFormRef.value.validate()
  // 发送登录请求
  try {
    await userStore.userLogin(loginForm.value)
    // 登录成功，跳转页面
    let redirect = route.query.redirect as string
    router.push(redirect || '/')
    ElNotification({
      message: '登录成功',
      type: 'success',
      title: `Hi,${getTime()}好`
    })
  }
  // 登录失败，提示错误信息
  catch (err) {
    ElNotification({
      message: (err as Error).message,
      type: 'error'
    })
  }
}
// 登录表单校验
const loginRules = reactive({
  username: [
    { required: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'change' }
  ],
  password: [
    { required: true, min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'change' }
  ]
})


</script>
<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login-form" :model="loginForm" :rules="loginRules" ref="loginFormRef" >
          <h1>hello</h1>
          <h2>欢迎学习vue3</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" placeholder="请输入密码" v-model="loginForm.password"
              show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="login-btn" type="primary" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  //‌自动缩放‌：保持图片原始比例缩放至完全覆盖容器
  background-size: cover;
}

.login-form {
  position: relative;
  width: 80%;
  top: 30vh;
  background: url('@/assets/images/login_form.png') no-repeat;
  background-size: cover;
  padding: 40px;

  h1 {
    color: white;
    font-size: 40px;
  }

  h2 {
    color: white;
    font-size: 20px;
    margin: 20px 0;
  }

  .login-btn {
    width: 100%;
  }
}
</style>